package com.soul.utils;

import org.springframework.util.DigestUtils;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class EncryptUtil {

    public static final String RSA = "RSA";
    public static final String AES = "AES";
    public static final String DES = "DES";
    public static final String DESEDE = "DESede";
    public static final String CIPHER_DESEDE = "DESede/ECB/PKCS5Padding";
    public static final String BASE_64 = "base64";
    public static final String HEX = "hex";
    public static final String HMAC_SHA_1 = "HmacSHA1";

    private EncryptUtil() {
        throw new IllegalStateException("Utility class");
    }

    public static String md5(String data) {
        return DigestUtils.md5DigestAsHex(data.getBytes());
    }

    public static String sha1(String data) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA");
            byte[] cipherBytes = messageDigest.digest(data.getBytes(StandardCharsets.UTF_8));
            return parseByte2HexStr(cipherBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String sha256(String data) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(data.getBytes(StandardCharsets.UTF_8));
            byte[] bytes = messageDigest.digest();
            return parseByte2HexStr(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String rsaSHA1(String data, String privateKey, String outputEncoding) {
        try {
            byte[] keyBytes = Base64.getDecoder().decode(privateKey.getBytes());
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
            PrivateKey priKey = KeyFactory.getInstance(RSA).generatePrivate(keySpec);
            Signature signature = Signature.getInstance("SHA1withRSA");
            signature.initSign(priKey);
            signature.update(data.getBytes(StandardCharsets.UTF_8));
            byte[] signs = signature.sign();
            if (BASE_64.equals(outputEncoding)) {
                return Base64.getEncoder().encodeToString(signs);
            }
            return parseByte2HexStr(signs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * RSA-SHA1
     */
    private static boolean verifyWhenSha1Sign(String content, String sign, PublicKey publicKey, String inputEncoding) {
        try {
            byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);
            Signature signature = Signature.getInstance("SHA1withRSA");
            signature.initVerify(publicKey);
            signature.update(contentBytes);
            if (BASE_64.equals(inputEncoding)) {
                return signature.verify(Base64.getDecoder().decode(sign));
            }
            return signature.verify(parseHexStr2Byte(sign));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String rsaSHA256(String data, String privateKey, String outputEncoding) {
        try {
            byte[] keyBytes = Base64.getDecoder().decode(privateKey.getBytes());
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
            PrivateKey priKey = KeyFactory.getInstance(RSA).generatePrivate(keySpec);
            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initSign(priKey);
            signature.update(data.getBytes(StandardCharsets.UTF_8));
            byte[] signs = signature.sign();
            if (BASE_64.equals(outputEncoding)) {
                return Base64.getEncoder().encodeToString(signs);
            }
            return parseByte2HexStr(signs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * RSA-SHA256
     */
    private static boolean verifyWhenSha256Sign(String content, String sign, PublicKey publicKey, String inputEncoding) {
        try {
            byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);
            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initVerify(publicKey);
            signature.update(contentBytes);
            if (BASE_64.equals(inputEncoding)) {
                return signature.verify(Base64.getDecoder().decode(sign));
            }
            return signature.verify(parseHexStr2Byte(sign));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String rsaMD5(String data, String privateKey, String outputEncoding) {
        try {
            byte[] keyBytes = Base64.getDecoder().decode(privateKey.getBytes());
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
            PrivateKey priKey = KeyFactory.getInstance(RSA).generatePrivate(keySpec);
            Signature signature = Signature.getInstance("MD5withRSA");
            signature.initSign(priKey);
            signature.update(data.getBytes(StandardCharsets.UTF_8));
            byte[] signs = signature.sign();
            if (BASE_64.equals(outputEncoding)) {
                return Base64.getEncoder().encodeToString(signs);
            }
            return parseByte2HexStr(signs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * RSA-MD5
     */
    private static boolean verifyWhenMD5Sign(String content, String sign, PublicKey publicKey, String inputEncoding) {

        try {
            byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);
            Signature signature = Signature.getInstance("MD5withRSA");
            signature.initVerify(publicKey);
            signature.update(contentBytes);
            if (BASE_64.equals(inputEncoding)) {
                return signature.verify(Base64.getDecoder().decode(sign));
            }
            return signature.verify(parseHexStr2Byte(sign));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String hmacSHA1(String data, String secretKey, String outputEncoding) {
        try {
            Mac mac = Mac.getInstance(HMAC_SHA_1);
            SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(secretKey), HMAC_SHA_1);
            mac.init(secretKeySpec);
            byte[] bytes = mac.doFinal(data.getBytes());
            if (BASE_64.equals(outputEncoding)) {
                return Base64.getEncoder().encodeToString(bytes);
            }
            return parseByte2HexStr(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String rsaPublicEncrypt(String publicKey, String data, String outputEncoding) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(RSA);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));
            RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
            Cipher cipher = Cipher.getInstance(RSA);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] bytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
            if (BASE_64.equals(outputEncoding)) {
                return Base64.getEncoder().encodeToString(bytes);
            }
            return parseByte2HexStr(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String rsaPublicDecrypt(String publicKey, String data, String inputEncoding) {
        try {
            byte[] dataBytes;
            if (BASE_64.equals(inputEncoding)) {
                dataBytes = Base64.getDecoder().decode(data);
            } else {
                dataBytes = parseHexStr2Byte(data);
            }

            KeyFactory keyFactory = KeyFactory.getInstance(RSA);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));
            RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
            Cipher cipher = Cipher.getInstance(RSA);
            cipher.init(Cipher.DECRYPT_MODE, key);
            return new String(cipher.doFinal(dataBytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String rsaPrivateEncrypt(String privateKey, String data, String outputEncoding) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(RSA);
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
            RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
            Cipher cipher = Cipher.getInstance(RSA);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] bytes = cipher.doFinal(data.getBytes());
            if (BASE_64.equals(outputEncoding)) {
                return Base64.getEncoder().encodeToString(bytes);
            }
            return parseByte2HexStr(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String rsaPrivateDecrypt(String privateKey, String data, String inputEncoding) {
        try {
            byte[] dataBytes;
            if (BASE_64.equals(inputEncoding)) {
                dataBytes = Base64.getDecoder().decode(data);
            } else {
                dataBytes = parseHexStr2Byte(data);
            }
            KeyFactory keyFactory = KeyFactory.getInstance(RSA);
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
            RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
            Cipher cipher = Cipher.getInstance(RSA);
            cipher.init(Cipher.DECRYPT_MODE, key);
            return new String(cipher.doFinal(dataBytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String aesEncrypt(String data, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance(AES);
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(password.getBytes());
            kgen.init(128, random);
            Cipher cipher = Cipher.getInstance(AES);
            cipher.init(Cipher.ENCRYPT_MODE, kgen.generateKey());
            return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String aesDecrypt(String data, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance(AES);
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(password.getBytes());
            kgen.init(128, random);
            Cipher cipher = Cipher.getInstance(AES);
            cipher.init(Cipher.DECRYPT_MODE, kgen.generateKey());
            return new String(cipher.doFinal(Base64.getDecoder().decode(data)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String desEncrypt(String data, String password) {
        try {
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
            Cipher cipher = Cipher.getInstance(DES);
            cipher.init(Cipher.ENCRYPT_MODE, keyFactory.generateSecret(new DESKeySpec(password.getBytes())), new SecureRandom());
            return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String desDecrypt(String data, String password) {
        try {
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
            Cipher cipher = Cipher.getInstance(DES);
            cipher.init(Cipher.DECRYPT_MODE, keyFactory.generateSecret(new DESKeySpec(password.getBytes())), new SecureRandom());
            return new String(cipher.doFinal(Base64.getDecoder().decode(data.getBytes())));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String des2Encrypt(String data, String password) {
        try {
            DESedeKeySpec deSedeKeySpec = new DESedeKeySpec(password.getBytes(StandardCharsets.UTF_8));
            // 创建密匙工厂
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DESEDE);
            // 将 DESedeKeySpec 对象转换成 SecretKey 对象
            SecretKey secureKey = keyFactory.generateSecret(deSedeKeySpec);
            // Cipher对象实际完成解密操作
            Cipher cipher = Cipher.getInstance(CIPHER_DESEDE);
            // 用密匙初始化 Cipher对象
            cipher.init(Cipher.ENCRYPT_MODE, secureKey);
            // 实例化负责加密/解密的Cipher工具类
            return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String parseByte2HexStr(byte[] buf) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toLowerCase());
        }
        return sb.toString();
    }

    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return new byte[0];
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
}
